package JsonStr2Json;

import javax.swing.JFrame;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;

import javax.swing.JTextArea;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.BorderFactory;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.LayoutStyle.ComponentPlacement;
import java.awt.GridLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowStateListener;
import java.util.Iterator;
import java.util.Optional;
import java.util.Set;

import javax.swing.SpringLayout;
import javax.swing.border.Border;

import org.apache.commons.lang.StringUtils;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.util.JSONTokener;

import javax.swing.JLabel;
import javax.swing.JOptionPane;

public class JsonFomatterMain extends JFrame {

    /**
    *
    */
    private static final long serialVersionUID = 68971280247464076L;

    public JsonFomatterMain() {

        this.initComponent();
        this.setVisible(true);
        this.setTitle("JSON转换器");
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        getContentPane().setLayout(new BorderLayout(0, 0));
    }
    private JTextArea textArea = null;
    private JTextArea textArea_1 = null;
    private void initComponent() {
        JPanel panel = new JPanel();
        getContentPane().add(panel, BorderLayout.NORTH);

        JButton btnNewButton = new JButton("转换");
        btnNewButton.addActionListener(new ActionListener() {
            
            @Override
            public void actionPerformed(ActionEvent e) {
                StringBuilder result = new StringBuilder();
                fomatter(result, textArea.getText());
                textArea_1.setText("");
                textArea_1.setText(result.toString());
            }
        });
        panel.add(btnNewButton);

        JPanel panel_1 = new JPanel();
        getContentPane().add(panel_1, BorderLayout.CENTER);
        panel_1.setLayout(new GridLayout(1, 1, 10, 10));

        Border border = BorderFactory.createLineBorder(Color.BLACK);

        textArea = new JTextArea();
        textArea.setLineWrap(true);
        textArea.setWrapStyleWord(true);
        textArea.setBorder(BorderFactory.createCompoundBorder(border, BorderFactory.createEmptyBorder(10, 10, 10, 10)));
        JScrollPane leftScroll = new JScrollPane(textArea);
        panel_1.add(leftScroll);

        textArea_1 = new JTextArea();
        textArea_1
            .setBorder(BorderFactory.createCompoundBorder(border, BorderFactory.createEmptyBorder(10, 10, 10, 10)));
        JScrollPane rightScroll = new JScrollPane(textArea_1);
        panel_1.add(rightScroll);

        JPanel panel_2 = new JPanel();
        getContentPane().add(panel_2, BorderLayout.SOUTH);

//        JLabel lblNewLabel = new JLabel("213123");
//        panel_2.add(lblNewLabel);

        this.setUndecorated(false);
//        Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
//        this.setSize(d.width, d.height);
        this.setSize(800, 480);
        this.setResizable(false);
    }
    
    @SuppressWarnings("unchecked")
    private static void handJsonObj(StringBuilder result, JSONObject jsonObject) {
        if (null != jsonObject) {
            Set<String> keySet = jsonObject.keySet();
            for(String key : keySet){
                String optString = jsonObject.optString(key);
                if (StringUtils.isBlank(optString)) {
                    result.append(String.format("json.put(\"%s\", \"%s\")", key, optString));
                    result.append("\n");
                    continue;
                }
                Object listArray = new JSONTokener(jsonObject.optString(key)).nextValue();
                if (listArray instanceof JSONArray) {
                    result.append("\n");
                    JSONArray jsonArray = (JSONArray)listArray;
                    for (int k = 0; k < jsonArray.size(); k++) {
                        JSONObject parameterObject = jsonArray.getJSONObject(k);
                        StringBuilder subObj = new StringBuilder();
                        result.append(String.format("//这是 %s 的子项\n", key));
                        handJsonObj(subObj, parameterObject);
                        result.append(subObj);
                    }
                    result.append("\n");
                } else if (listArray instanceof JSONObject) {
                    StringBuilder subObj = new StringBuilder();
                    result.append(String.format("//这是 %s 的子项 \n", key));
                    handJsonObj(subObj, (JSONObject)listArray);
                    result.append(subObj);
                } else {
                    result.append(String.format("json.put(\"%s\", \"%s\");", key, listArray));
                    result.append("\n");
                }
            }
        }
    }
    
    private void fomatter(StringBuilder result, String text) {
        String start = StringUtils.substring(text, 0, 1);
        if ("{".equals(start)) {
            handJsonObj(result, JSONObject.fromObject(text));
        } else if ("[".equals(start)) {
        } else {
            JOptionPane.showMessageDialog(this, "JSON 必须是 “[” 或者 “{” 开头", "提示",JOptionPane.INFORMATION_MESSAGE);  
        }
    }
    
//    private static String text = "{\"scm\":[{\"key1\":\"vlaue1\",\"key2\":\"vlaue2\"},{\"key11\":\"vlaue11\",\"key22\":\"vlaue22\"}]}\r\n";
//    private static String text = "{\"SKU\":\"SIMG05040001\",\"GoodsCode\":\"SIMG05040001\",\"AvailableQty\":56,\"StockQty\":56,\"UsedQty\":0,\"StockUnitNo\":\"US-NY-A01-001\",\"StockID\":5}";
//    private static String text = "";
    
    public static void main(String[] args) {
        new JsonFomatterMain();
    }
}
